﻿#region Licence
// <copyright file="Core/MainWindow.xaml.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Core.Class;
using Core.Class.Synchronize;
using Core.Enums;
using Core.Helpers;
using Core.Messages;
using Core.ViewModel;
using Core.ViewModel.Controls;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using Helpers.Extensions;
using Helpers.Mef;
using Helpers.Messages;
using Interfaces;
using Interfaces.Enums;
using Navegar;

#endregion

namespace Core.Views
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IPartImportsSatisfiedNotification
    {
        /// <summary>
        /// Templates des vues
        /// </summary>
        [ImportMany("ViewTemplatesModules", typeof(ResourceDictionary))]
        public IEnumerable<ResourceDictionary> DataTemplatesViewModules { get; set; }

        /// <summary>
        /// Converters des modules
        /// </summary>
        [ImportMany("ConvertersModules", typeof(ResourceDictionary))]
        public IEnumerable<ResourceDictionary> ConvertersViewModules { get; set; }

        /// <summary>
        /// DataTemplate pour les modules : permet d'afficher les résultats de recherche, centraliser des templates utilisables ailleurs
        /// </summary>
        [ImportMany("DataTemplatesModules", typeof(ResourceDictionary))]
        public IEnumerable<ResourceDictionary> DataTemplatesModules { get; set; } 

        /// <summary>
        /// Permet d'indiquer que l'on ai déja en cours de fermeture
        /// </summary>
        private bool _onClosing = false;

        /// <summary>
        /// 
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            CompositionInitializer.AddPartAndComposeContainer(this);
            NetworkStatus.AvailabilityChanged += NetworkStatusOnAvailabilityChanged;
            this.Loaded += OnLoaded;
        }

        private void NetworkStatusOnAvailabilityChanged(object sender, NetworkStatusChangedArgs networkStatusChangedArgs)
        {
            CurrentParametersInRunning.IsNetworkAvailable = NetworkStatus.IsAvailable;
            CurrentParametersInRunning.IsSqlServerOnline = NetworkHelper.SetStatusSqlServer();

            if (!NetworkStatus.IsAvailable)
            {
                Application.Current.Dispatcher.Invoke((Action) (() => SimpleIoc.Default.GetInstance<IServiceChildWindow>()
                    .NotificationMessage(
                        SimpleIoc.Default.GetInstance<IServiceLocalize>()
                            .LocalizedFromKey("Generic_OnChangedNetworkStatusToOffline"),
                        SimpleIoc.Default.GetInstance<IServiceLocalize>().LocalizedFromKey("MainCoreTitle"),
                        CallBackOnNetworkChangedStatusMessage, NotificationMessageIconEnum.Error)));
            }
            else
            {
                Application.Current.Dispatcher.Invoke((Action)(() => SimpleIoc.Default.GetInstance<IServiceChildWindow>()
                    .NotificationMessage(
                        SimpleIoc.Default.GetInstance<IServiceLocalize>()
                            .LocalizedFromKey("Generic_OnChangedNetworkStatusToOnline"),
                        SimpleIoc.Default.GetInstance<IServiceLocalize>().LocalizedFromKey("MainCoreTitle"), NotificationMessageIconEnum.Information)));
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            SimpleIoc.Default.GetInstance<INavigation>().NavigateTo<ConnectionViewModel>();
            Messenger.Default.Register<RefreshBarreEtatMessage>(this, OnRefreshBarreEtat);
        }

        /// <summary>
        /// Lors de la fermeture de l'application on va lancer une synchronisation des données
        /// </summary>
        /// <param name="e"></param>
        protected async override void OnClosing(CancelEventArgs e)
        {
            if (SimpleIoc.Default.GetInstance<IServiceParametre>()
                    .GetValueParameter<bool>((int) EParameters.UseSynchronization, TypeModulesEnum.Core))
            {
                //On va lancer la synchronisation avec le serveur
                if (NetworkStatus.IsAvailable && !_onClosing)
                {
                    e.Cancel = true;
                    if (!await Synchronize())
                    {
                        SimpleIoc.Default.GetInstance<IServiceChildWindow>()
                            .NotificationMessage(
                                SimpleIoc.Default.GetInstance<IServiceLocalize>()
                                    .LocalizedFromKey("Generic_ErrorOnSynchronisation"),
                                SimpleIoc.Default.GetInstance<IServiceLocalize>().LocalizedFromKey("MainCoreTitle"),
                                CallBackOnErrorSynchroMessage, NotificationMessageIconEnum.Error);

                        SimpleIoc.Default.GetInstance<IServiceBarreEtat>().ClearContentFree();
                    }
                    else
                    {
                        SimpleIoc.Default.GetInstance<IServiceBarreEtat>().ClearContentFree();

                        _onClosing = true;
                        Application.Current.Shutdown();
                    }
                }
                else
                {
                    _onClosing = true;
                    Application.Current.Shutdown();
                }
            }
            else
            {
                _onClosing = true;
                Application.Current.Shutdown();
            }
        }

        private void CallBackOnErrorSynchroMessage()
        {
            _onClosing = true;
            Application.Current.Shutdown();
        }

        private void CallBackOnNetworkChangedStatusMessage()
        {
            _onClosing = true;
            Application.Current.Shutdown();
        }

        public void OnImportsSatisfied()
        {
            //Template des vues
            foreach (var resourceDictionary in DataTemplatesViewModules)
            {
                this.Resources.MergedDictionaries.Add(resourceDictionary);
            }

            //Converters des modules
            foreach (var resourceDictionary in ConvertersViewModules)
            {
                Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
            }

            //DataTemplates des modules
            foreach (var resourceDictionary in DataTemplatesModules)
            {
                Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
            }
        }

        private void OnRefreshBarreEtat(RefreshBarreEtatMessage obj)
        {
            if (!obj.IsClear)
            {
                this.TextBarreEtat.Text = obj.Message;
                this.IconBarreEtat.Data = obj.IconGeometry;
            }
            else
            {
                this.TextBarreEtat.Text = string.Empty;
                this.IconBarreEtat.Data = null;
            }
            this.TextBarreEtat.Refresh();
            this.IconBarreEtat.Refresh();
        }

        /// <summary>
        /// lance la synchronisation des données
        /// </summary>
        /// <returns></returns>
        private async Task<bool> Synchronize()
        {
            //Mise à jour de la barre d'état
            SimpleIoc.Default.GetInstance<IServiceBarreEtat>().ClearContentFree();
            SimpleIoc.Default.GetInstance<IServiceBarreEtat>().ClearMessage();
            SimpleIoc.Default.GetInstance<IServiceBarreEtat>().SetContentFree(new SynchronisationDatasViewModel());

            return await Synchronisation.Synchronize();
        }

        private void MainWindow_OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                Messenger.Default.Send<KeyEventsMessage>(new KeyEventsMessage() { KeyEventArguments = e, KeyPressed = true });
            }
        }

        private void MainWindow_OnPreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                Messenger.Default.Send<KeyEventsMessage>(new KeyEventsMessage() { KeyEventArguments = e, KeyPressed = false });
            }
        }

        private void SearchOnKeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrEmpty(((TextBox)sender).Text) && e.Key == Key.Enter)
            {
                ((MainViewModel) this.DataContext).UnifiedSearch();
            }
        }
    }
}
